import { EventBase, IGridController } from '@ibiz-template/runtime';
import { FormMDCtrlControlController } from '../form-mdctrl-control/form-mdctrl-control.controller';

/**
 * 表单多数据部件表格类型控制器
 *
 * @author zk
 * @date 2023-07-28 08:07:57
 * @export
 * @class FormMDCtrlGridController
 * @extends {EditFormController}
 * @implements {IFormController}
 */
export class FormMDCtrlGridController extends FormMDCtrlControlController {
  /**
   * 表格控制器
   *
   * @author zk
   * @date 2023-07-30 07:07:18
   * @type {IGridController}
   * @memberof FormMDCtrlGridController
   */
  gridController!: IGridController;

  /**
   * 表格选中数据
   *
   * @author zk
   * @date 2023-07-30 07:07:45
   * @type {IData[]}
   * @memberof FormMDCtrlGridController
   */
  selectData: IData[] = [];

  /**
   * uiState
   *
   * @author zk
   * @date 2023-07-31 12:07:57
   * @type {{ isSelect: boolean }}
   * @memberof FormMDCtrlGridController
   */
  state: { isSelect: boolean } = { isSelect: false };

  /**
   * 表格挂载后把控制器抛出来
   *
   * @author zk
   * @date 2023-07-30 07:07:25
   * @param {EventBase} event
   * @memberof FormMDCtrlGridController
   */
  onGridMounted(event: EventBase): void {
    this.gridController = event.ctrl as IGridController;
  }

  /**
   * 表格选中事件
   *
   * @author zk
   * @date 2023-07-30 07:07:06
   * @param {EventBase} event
   * @memberof FormMDCtrlGridController
   */
  onSelectionChange(event: EventBase): void {
    this.state.isSelect = event.data.length > 0;
  }

  /**
   * 数据删除
   *
   * @author zk
   * @date 2023-07-30 05:07:32
   * @param {number} index
   * @memberof FormMDCtrlController
   */
  onDataRemove(): void {
    this.gridController.remove();
    this.parent.state.contentCtrlData = this.gridController.state.items;
    this.parent.setFormDataValue();
  }

  /**
   * 内部表单数据发生改变，同步contentCtrlData并设置外部表单值
   *
   * @author zk
   * @date 2023-07-30 05:07:18
   * @param {IData[]} data
   * @memberof FormMDCtrlController
   */
  onDataChange(data: IData[]): void {
    this.parent.state.contentCtrlData = data;
    this.parent.setFormDataValue();
  }

  /**
   * 初始化数据
   *
   * @author zk
   * @date 2023-07-30 08:07:32
   * @memberof FormMDCtrlContentTypeController
   */
  async initData(): Promise<void> {
    this.gridController.load();
  }

  /**
   * 数据插入
   *
   * @author zk
   * @date 2023-07-31 12:07:27
   * @param {IData} [data]
   * @memberof FormMDCtrlContentTypeController
   */
  async onDataInsert(): Promise<void> {
    await this.gridController.newRow();
    this.parent.state.contentCtrlData = this.gridController.state.items;
    this.parent.setFormDataValue();
  }
}
